var express = require("express");
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
var fs = require("fs");
var session = require("express-session");
var app = express();
//var redisStore = require("connect-redis")(session);

//app.use(session({
//store:new redisStore({host:"127.0.0.1",port:"3000"}),
//secret: 'somesecrettoken',
//resave: true,
//saveUninitialized: true
//}));
app.use(session({
	secret: 'recommand 128 bytes random string', // 建议使用 128 个字符的随机字符串
	cookie: { maxAge: 60 * 1000 *30},
}));
app.use(express.static("static"));
//对于backbone提交的数据默认数据编码方式是json格式，所以需要使用json编码。编码后的数据：
//{'name1':value1,'name2':value2}
app.use(bodyParser.json());

mongoose.connect("mongodb://localhost/shangqiang");

var db = mongoose.connection;
db.on("open", function() {
	console.log("数据库打开成功");
});

db.on("error", function() {
	console.log("数据库打开失败");
});

db.on('connected', function() {
	console.log('Connection success!');
});

db.on('disconnected', function() {
	console.log('Connection disconnected');
});
// 建立3个表
// 用户(user):
//     id
//     username
//     password
//     registed_time
// 话题(topic):
//     id
//     title
//     created_time
//     owner
// 消息(message):
//     id
//     content
//     topic_id
//     user_id
//     created_time
var user = mongoose.model("users", {
	//  id: Number,
	username: String,
	password: String,
	registed_time: String
});

var topic = mongoose.model("topics", {
	//  id: Number,
	title: String,
	owner: String,
	created_time: String,

});

var message = mongoose.model("messages", {
	//  id: Number,
	content: String,
	topic_id: String,
	username: String,
	created_time: String
});

//注册接口
app.post("/user", function(req, res) {
	console.log(req.body);
	var username = req.body.username;
	console.log(username);

	var password = req.body.password;
	console.log(password);

	var password_repeat = req.body.password_repeat;
	if(password != password_repeat) {
		console.log("两次密码不对");

		//				返回密码错误信息
	}
	user.find({ username: username }).exec(function(err, data) {
		if(err) {
			console.log("根据用户名查找出错");

			//数据库出错
		} else {
			if(data.length > 0) {
				console.log("用户存在==========注册接口");

				//该用户已存在
			} else {
				console.log("开始搞事")
				//								var newDate = Date();
				var newUser = new user({
					username: username,
					password: password,
					registed_time: new Date(),
				});
				newUser.save(function(err) {
					if(err) {

					} else {
						user.findOne({ username: username }).exec(function(err, data) {
							if(data) {
								console.log("搞事成功，执行返回数据操作");
								data = data.toObject();
								data.id = data._id.toString();
								delete data._id;
								req.session.login = 1;
								req.session.user = data;
								res.json({result: 'success', msg: '注册成功已跳转登陆', data: data});
							}
						});
					}
				});
			}
		}
	});
});

//登陆接口    model.save()
app.post("/login", function(req, res) {
	console.log("开始登陆");
	console.log(req.body);
	var username = req.body.username;
	console.log(username);

	var password = req.body.password;
	console.log(password);

	user.findOne({ username: username, password: password }).exec(function(err, data) {
		if(err) {
			console.log("根据用户名查找出错");
			//数据库出错
		}
		if(data) {
			console.log("登陆成功，执行返回数据操作");
			data = data.toObject();
			data.id = data._id.toString();
			delete data._id;
			req.session.login = 1;
			req.session.user = data;
//			res.json({ result: 'success', msg: '很皮，已登陆', data: data });
			res.json({data: data });
			
		}
	});
});

//获取所有话题    对应 collection.fetch()
app.get("/topic", function(req, res) {
	topic.find().exec(function(err, data) {
		if(err) {

		} else {
			if(data.length > 0) {
				var arr = data.map((aData) => {
					//toObject()是把mongo中的数据模型对象转化为js对象
					aData = aData.toObject();
					aData.id = aData._id.toString();
					delete aData._id;
					return aData;
				});
//				res.json({ result: 'success', msg: '所有topic已返回', data: arr });
				res.send(arr);
			}
		}

	});
});

app.get("/topic/:id", function(req, res) {

//			保存成功后,找到这条数据并返回
			topic.find({"_id": mongoose.Types.ObjectId(req.params.id)}).exec(function(err, data) {
				if(err) {
					console.log("根据_id查找出错");
					//数据库出错
				}
				if(data) {
					var arr = data.map((aData) => {
						//toObject()是把mongo中的数据模型对象转化为js对象
						aData = aData.toObject();
//						aData.id = aData._id.toString();
//						delete aData._id;
						return aData;
					});
					res.json({data: arr[0]});
				}
			});

});

//新增一个话题 对应Model.save()，
app.post("/topic", function(req, res) {
	console.log(req.session.user);
	var title = req.body.title;
//	var owner = req.body.owner;
	var newTopic = new topic({
		title: title,
		owner: req.session.user.username,
		created_time: new Date()
	});
	newTopic.save(function(err) {
		if(err) {

		} else {
//			保存成功后,找到这条数据并返回
			topic.findOne({ title: title, owner: req.session.user.username }).exec(function(err, data) {
				if(err) {
					console.log("根据用户名查找出错");
					//数据库出错
				}
				if(data) {
					console.log("新增话题成功 数据返回");
					data = data.toObject();
					data.id = data._id.toString();
					delete data._id;
					res.json({data: data});
				}
			});
		}
	});
});

//获取某话题所有消息    对应 collection.fetch()
app.get("/message", function(req, res) {
	console.log("获取话题所有消息 请求已收到");
	console.log("topic_id  body"+ req.query.topic_id);
	message.find({topic_id: req.query.topic_id}).exec(function(err, data) {
		if(err) {
			console.log("获取所有消息 数据库查询失败");
		} else {
			console.log("获取所有消息 数据库查询成功");
			if(data.length > 0) {
				var arr = data.map((aData) => {
					//toObject()是把mongo中的数据模型对象转化为js对象
					aData = aData.toObject();
					aData.id = aData._id.toString();
					delete aData._id;
					if(aData.username == req.session.user.username){
						aData.is_mime = 1;
					}else{
						aData.is_mine = 0;
					}
					return aData;
				});
				res.send(arr);
			}else{
			console.log("没查询到任何消息,伪装一条数据返回");
				var xxx = [{content: null,
							topic_id: null,
							username: null,
							created_time: null,
				}]
				res.send(xxx);
			}

			
		}

	});
});

//给某话题新增一条消息 对应Model.save()，
app.post("/message", function(req, res) {
	var content = req.body.content;
	var topic_id = req.body.topic_id;
	var username = req.session.user.username;
	var newMessage = new message({
		content: content,
		topic_id: topic_id,
		username: username,
		created_time: new Date(),
	});
	console.log(newMessage);
	newMessage.save(function(err) {
		if(err) {

		} else {
			res.json({ result: 'success', msg: '新消息保存成功' });
		}
	});
});

// 测试接口
app.get("/user", function(req, res) {
	console.log(req.query);
	var username = req.query.username;
	console.log(username);

	var password = req.query.password;
	console.log(password);

	var password_repeat = req.query.password_repeat;
	if(password != password_repeat) {
		console.log("两次密码不对");

		//				返回密码错误信息
	}
	user.find({ username: username }).exec(function(err, data) {
		if(err) {
			console.log("根据用户名查找出错");

			//数据库出错
		} else {
			if(data.length > 0) {
				console.log("用户存在=======测试接口");
//				var result = null;
				res.json({data: null });
				
			}
				

				//该用户已存在
			else {
				console.log("开始搞事")
				//								var newDate = Date();
				var newUser = new user({
					username: username,
					password: password,
					registed_time: new Date()
				});
				newUser.save(function(err) {
					if(err) {

					} else {
						user.findOne({ username: username }).exec(function(err, data) {
							if(data) {
								console.log("搞事成功，执行返回数据操作");
								data = data.toObject();
								data.id = data._id.toString();
								delete data._id;
								req.session.login = 1;
								req.session.user = data;
								res.json({ result: 'success', msg: '跳转登陆了', data: data });
							}
						});
					}
				});
			}
		}
	});
});

app.listen(3000, function() {

	console.log('server running...');
});
